package cn.edu.stu.syllabus.library.star;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.edu.stu.syllabus.R;
import cn.edu.stu.syllabus.adapters.BookAdapter;
import cn.edu.stu.syllabus.base.BaseActivity;
import cn.edu.stu.syllabus.base.BaseFragment;
import cn.edu.stu.syllabus.base.BaseQuickClickAdapter;
import cn.edu.stu.syllabus.base.StoreProxy;
import cn.edu.stu.syllabus.library.detail.BookDetailActivity;
import cn.edu.stu.syllabus.repository.library.local.BookEntry;
import cn.edu.stu.syllabus.utils.ListUtils;
import cn.edu.stu.syllabus.utils.RecyclerPaddingUtils;
import cn.edu.stu.syllabus.widgets.CustomLoadMoreView;
import cn.edu.stu.syllabus.widgets.CustomLayoutManger;

import static cn.edu.stu.syllabus.utils.NullPointerUtils.checkNotNull;

/**
 * Created by daidaijie on 2017/3/31.
 */

public class BookStarFragment extends BaseFragment implements BookStarContract.View, BaseQuickAdapter.RequestLoadMoreListener, BaseActivity.OnToolbarDoubleClickListener {

    @BindView(R.id.bookStarRecyclerView)
    RecyclerView mBookStarRecyclerView;

    private BookAdapter mBookAdapter;

    private BookStarContract.Presenter mPresenter;

    View mEmptyView;

    View mErrorView;

    int lastOpenPosition = -1;

    private boolean mRecyclerViewClickable;

    private final int REQUEST_OPEN_DETAIL = 200;

    public static BookStarFragment newInstance() {
        BookStarFragment fragment = new BookStarFragment();
        return fragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_book_star;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        CustomLayoutManger customLayoutManger
                = new CustomLayoutManger(mActivity);
        customLayoutManger.setSpeedFast();
        mBookStarRecyclerView.setLayoutManager(customLayoutManger);


        mBookAdapter = new BookAdapter(new ArrayList<BookEntry>(), false);
        mBookAdapter.setLoadMoreView(new CustomLoadMoreView());
        mBookStarRecyclerView.setAdapter(mBookAdapter);

        RecyclerPaddingUtils.fitRecyclerViewPadding(mActivity, mBookStarRecyclerView);

        final String[] items = {"取消收藏"};

        mRecyclerViewClickable = true;
        mBookAdapter.setOnLoadMoreListener(this);
        mBookAdapter.setOnItemClickListener(new BaseQuickClickAdapter.OnItemClickListener<BookEntry>() {
            @Override
            public void onItemClick(BookEntry bookEntry, int position) {
                if (!mRecyclerViewClickable) {
                    return;
                }
                lastOpenPosition = position;
                Intent intent = BookDetailActivity.newIntent(mActivity, bookEntry);
                BookStarFragment.this.startActivityForResult(intent, REQUEST_OPEN_DETAIL);
            }
        });

        mBookAdapter.setOnItemLongClickListener(new BaseQuickClickAdapter.OnItemLongClickListener<BookEntry>() {
            @Override
            public boolean onItemLongClick(final BookEntry bookEntry, final int position) {
                if (!mRecyclerViewClickable) {
                    return false;
                }
                final AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                        .setTitle("请选择操作")
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    mPresenter.unstarBook(bookEntry, position);
                                }
                            }
                        })
                        .create();
                alertDialog.show();
                return true;
            }
        });

        mEmptyView = LayoutInflater.from(mActivity).inflate(R.layout.empty_view
                , (ViewGroup) mBookStarRecyclerView.getParent(), false);
        mErrorView = LayoutInflater.from(mActivity).inflate(R.layout.error_view
                , (ViewGroup) mBookStarRecyclerView.getParent(), false);
        TextView emptyTextView = (TextView) mEmptyView.findViewById(R.id.emptyTextView);
        emptyTextView.setText("目前还没有收藏，快去添加吧");

        TextView errorTextView = (TextView) mErrorView.findViewById(R.id.errTextView);
        errorTextView.setText("加载失败，请点击重试");
        mErrorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoadMoreRequested();
            }
        });

        StoreProxy.onRestoreInstanceState(savedInstanceState, mPresenter);
        mPresenter.subscribe();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        StoreProxy.onSaveInstanceState(outState, mPresenter);
    }

    @Override
    public void onDestroyView() {
        mPresenter.unsubscribe();
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_OPEN_DETAIL
                && resultCode == BookDetailActivity.RESULT_STAR_STATE_CHANGE) {
            boolean isStar = data.getBooleanExtra(BookDetailActivity.EXTRA_IS_STAR, false);
            Logger.e("isStar: " + isStar);
            if (isStar) {
                movePositionToTop(lastOpenPosition);
            } else {
                removeUnstarBook(lastOpenPosition);
            }
        }
    }

    private void movePositionToTop(int position) {
        mRecyclerViewClickable = false;
        mBookAdapter.movePositionToTop(position);
        mRecyclerViewClickable = true;
    }


    @Override
    public void setPresenter(BookStarContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @Override
    public void showDataEmpty() {
        mBookAdapter.setEmptyView(mEmptyView);
    }

    @Override
    public void showDataError() {
        mBookAdapter.setEmptyView(mErrorView);
    }

    @Override
    public void setBookList(List<BookEntry> bookEntries) {
        mBookAdapter.setNewData(bookEntries);
    }

    @Override
    public void appendBookList(List<BookEntry> bookEntries) {
        mBookAdapter.addData(bookEntries);
        mBookAdapter.loadMoreComplete();
    }

    @Override
    public void showLoadingFail() {
        mBookAdapter.loadMoreFail();
    }

    @Override
    public void showLoadingEnd() {
        mBookAdapter.loadMoreEnd();
    }

    @Override
    public void removeUnstarBook(int position) {
        if (position == -1) {
            return;
        }
        mRecyclerViewClickable = false;
        mBookAdapter.remove(position);
        if (ListUtils.getListSizeSafety(mBookAdapter.getData()) == 0) {
            mBookAdapter.setEmptyView(mEmptyView);
        }
        mRecyclerViewClickable = true;
    }


    @Override
    public void onLoadMoreRequested() {
        mPresenter.loadStarBookEntries();
    }

    @Override
    public void onToolbarDoubleClick() {
        mBookStarRecyclerView.smoothScrollToPosition(0);
    }
}
